package com.jcbase.controller.sys;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.log4j.Logger;

import com.jcbase.core.auth.anno.RequiresPermissions;
import com.jcbase.core.controller.JCBaseController;
import com.jcbase.core.pojo.Obj;
import com.jcbase.core.pojo.User;
import com.jcbase.core.util.AdUtil;
import com.jcbase.core.util.IWebUtils;
import com.jcbase.core.util.ImportExcelUtil;
import com.jcbase.core.view.InvokeResult;
import com.jcbase.job.AdUserInJob;
import com.jcbase.job.DataSourceInJob;
import com.jcbase.job.SiteSourceInJob;
import com.jcbase.job.TaskManage;
import com.jcbase.model.SysConfig;
import com.jcbase.model.SysConfigAd;
import com.jcbase.model.SysConfigDatasource;
import com.jcbase.model.SysGroup;
import com.jcbase.model.SysObj;
import com.jcbase.model.SysSite;
import com.jcbase.model.SysUser;
import com.jfinal.upload.UploadFile;

public class SysConfigController extends JCBaseController {
    private static Logger log = Logger.getLogger(AdUserInJob.class);

    @RequiresPermissions(value = { "/sys/config" })
    public void index() {

	List<SysConfig> sysConfig = SysConfig.me.find("select * from sys_config where param = 'host'");
	if (sysConfig.get(0).get("value") != null) {
	    setAttr("host", sysConfig.get(0).get("value"));
	}

	render("sys_config.jsp");
    }

    @RequiresPermissions(value = { "/sys/config" })
    public void siteConfigView() {
	List<SysConfigDatasource> databases = SysConfigDatasource.dao
		.find("select * from sys_config_datasource where id = 2");

	if (!CollectionUtils.isEmpty(databases)) {
	    SysConfigDatasource database = databases.get(0);
	    setAttr("data_host", database.getHost());
	    setAttr("data_user", database.getUser());
	    setAttr("data_password", database.getPassword());
	    setAttr("circle", database.getCircle());
	}
	render("sys_config_site.jsp");
    }

    public void loginAd() {

	SysConfigAd sysConfigAd = SysConfigAd.dao.findFirst("select * from sys_config_ad");
	if (sysConfigAd != null) {
	    setAttr("ad_host", sysConfigAd.getAdHost());
	    setAttr("ad_user", sysConfigAd.getAdUser());
	    setAttr("ad_password", sysConfigAd.getAdPwd());
	    setAttr("ad_safe_level", sysConfigAd.getAdSafeLevel());
	    setAttr("ad_dc", sysConfigAd.getAdDc());
	    setAttr("circle", sysConfigAd.getCircle());
	}

	render("sys_config_ad.jsp");
    }

    public void saveAdConfig() {
	String ad_host = this.getPara("host");
	String ad_user = this.getPara("user");
	String ad_password = this.getPara("password");
	String safeLevel = this.getPara("safeLevel");
	String ad_dc = this.getPara("dc");
	String circle = this.getPara("circle");

	SysConfigAd sysConfigAd = SysConfigAd.dao.findFirst("select * from sys_config_ad");
	if (sysConfigAd == null) {
	    sysConfigAd = new SysConfigAd();
	    sysConfigAd.set("ad_host", ad_host);
	    sysConfigAd.set("ad_user", ad_user);
	    sysConfigAd.set("ad_pwd", ad_password);
	    sysConfigAd.set("ad_safe_level", safeLevel);
	    sysConfigAd.set("ad_dc", ad_dc);
	    sysConfigAd.set("circle", Integer.parseInt(circle));
	    sysConfigAd.save();
	} else {
	    sysConfigAd.set("ad_host", ad_host);
	    sysConfigAd.set("ad_user", ad_user);
	    sysConfigAd.set("ad_pwd", ad_password);
	    sysConfigAd.set("ad_safe_level", safeLevel);
	    sysConfigAd.set("ad_dc", ad_dc);
	    sysConfigAd.set("circle", Integer.parseInt(circle));
	    sysConfigAd.update();
	}
	Long time = 0L;
	if ("1".equals(circle)) {
	    time = 60 * 60 * 24 * 1000L;// 一天

	    TaskManage.addJob(new AdUserInJob(), time);
	    log.info("任务添加成功,周期为每天");
	    this.renderJson(InvokeResult.success());
	} else if ("2".equals(circle)) {
	    // 如果是手动同步则直接进行同步
	    time = 7 * 60 * 60 * 24 * 1000L;// 一周
	    TaskManage.addJob(new AdUserInJob(), time);
	    log.info("任务添加成功,周期为每周");
	    this.renderJson(InvokeResult.success());
	} else if ("3".equals(circle)) {
	    // 如果是手动同步则直接进行同步
	    AdUtil ad = new AdUtil();
	    if (ad.initLdap()) {
		List<User> userList = ad.GetADInfo(ad_dc, ad.ctx);
		SysGroup.me.insertUserGroup(userList);
		this.renderJson(InvokeResult.success(0, "初始化用户成功"));
	    } else {
		this.renderJson(InvokeResult.failure(-1, "连接ladp服务失败"));
	    }
	} else {
	    this.renderJson(InvokeResult.failure("操作失败"));
	}
	// 实例AD

    }

    public void datasource() {
	List<SysConfigDatasource> databases = SysConfigDatasource.dao.find("select * from sys_config_datasource");
	if (!CollectionUtils.isEmpty(databases)) {
	    SysConfigDatasource database = databases.get(0);
	    setAttr("data_host", database.getHost());
	    setAttr("data_user", database.getUser());
	    setAttr("data_password", database.getPassword());
	    setAttr("circle", database.getCircle());
	}
	render("sys_config_datasource.jsp");
    }

    public void datasourceSave() throws ParseException {
	String data_host = this.getPara("data_host");
	String data_user = this.getPara("data_user");
	String data_password = this.getPara("data_password");
	String circle = this.getPara("circle");
	SysConfigDatasource dataBaseInfo = SysConfigDatasource.dao.findById(1);
	if (dataBaseInfo == null) {
	    dataBaseInfo = new SysConfigDatasource();
	    dataBaseInfo.setHost(data_host);
	    dataBaseInfo.setUser(data_user);
	    dataBaseInfo.setPassword(data_password);
	    dataBaseInfo.setCircle(Integer.parseInt(circle));
	    dataBaseInfo.save();
	} else {
	    dataBaseInfo.setHost(data_host);
	    dataBaseInfo.setUser(data_user);
	    dataBaseInfo.setPassword(data_password);
	    dataBaseInfo.setCircle(Integer.parseInt(circle));
	    dataBaseInfo.update();
	}
	Long time = 0L;
	if ("1".equals(circle)) {
	    time = 60 * 60 * 24 * 1000L;// 一天

	    TaskManage.addJob(new DataSourceInJob(data_host, data_user, data_password), time);
	    log.info("任务添加成功,周期为每天");
	    this.renderJson(InvokeResult.success());
	} else if ("2".equals(circle)) {
	    // 如果是手动同步则直接进行同步
	    time = 7 * 60 * 60 * 24 * 1000L;// 一周
	    TaskManage.addJob(new DataSourceInJob(data_host, data_user, data_password), time);
	    log.info("任务添加成功,周期为每周");
	    this.renderJson(InvokeResult.success());
	} else if ("3".equals(circle)) {
	    // 如果是手动同步则直接进行同步
	    if (SysObj.me.dataIn(data_host, data_user, data_password)) {
		this.renderJson(InvokeResult.success("数据库同步成功"));
	    } else {
		this.renderJson(InvokeResult.failure(-1, "操作失败"));
	    }
	} else {
	    this.renderJson(InvokeResult.failure(-1, "操作失败"));
	}

    }

    public void siteConfigSave() throws ParseException {
	String data_host = this.getPara("data_host");
	String data_user = this.getPara("data_user");
	String data_password = this.getPara("data_password");
	String circle = this.getPara("circle");
	SysConfigDatasource dataBaseInfo = SysConfigDatasource.dao.findById(2);
	if (dataBaseInfo == null) {
	    dataBaseInfo = new SysConfigDatasource();
	    dataBaseInfo.setHost(data_host);
	    dataBaseInfo.setUser(data_user);
	    dataBaseInfo.setPassword(data_password);
	    dataBaseInfo.setCircle(Integer.parseInt(circle));
	    dataBaseInfo.save();
	} else {
	    dataBaseInfo.setHost(data_host);
	    dataBaseInfo.setUser(data_user);
	    dataBaseInfo.setPassword(data_password);
	    dataBaseInfo.setCircle(Integer.parseInt(circle));
	    dataBaseInfo.update();
	}
	Long time = 0L;
	if ("1".equals(circle)) {
	    time = 60 * 60 * 24 * 1000L;// 一天
	    TaskManage.addJob(new SiteSourceInJob(data_host, data_user, data_password), time);
	    log.info("任务添加成功,周期为每天");
	    this.renderJson(InvokeResult.success());
	} else if ("2".equals(circle)) {
	    // 如果是手动同步则直接进行同步
	    time = 7 * 60 * 60 * 24 * 1000L;// 一周
	    TaskManage.addJob(new SiteSourceInJob(data_host, data_user, data_password), time);
	    log.info("任务添加成功,周期为每周");
	    this.renderJson(InvokeResult.success());
	} else if ("3".equals(circle)) {
	    // 如果是手动同步则直接进行同步
	    if (SysSite.me.dataIn(data_host, data_user, data_password)) {
		this.renderJson(InvokeResult.success("数据库同步成功"));
	    } else {
		this.renderJson(InvokeResult.failure(-1, "操作失败"));
	    }
	} else {
	    this.renderJson(InvokeResult.failure(-1, "操作失败"));
	}

    }

    @RequiresPermissions(value = { "/sys/config" })
    public void userConfig() throws FileNotFoundException, Exception {
	UploadFile uploadFile = this.getFile();
	File file = uploadFile.getFile();
	List<User> userList = new ArrayList<User>();
	if (file.exists()) {
	    List<List<String>> list = new ImportExcelUtil().getBankListByExcel(new FileInputStream(file),
		    file.getName());
	    for (List<String> object : list) {
		User user = new User();
		user.setUser(String.valueOf(object.get(0)));
		user.setGroup(String.valueOf(object.get(1)));
		user.setCommon(String.valueOf(object.get(2)));
		String params = "";
		for (String param : object) {
		    if (param.indexOf("=") >= 0) {
			params = params + param + ",";
		    }
		}
		if (params.length() >= 1) {
		    user.setParams(params.substring(0, params.length() - 1));
		}
		userList.add(user);
	    }
	}
	this.renderJson(SysGroup.me.insertUserGroup(userList));

    }

    @RequiresPermissions(value = { "/sys/config" })
    public void objConfig() throws FileNotFoundException, Exception {
	UploadFile uploadFile = this.getFile();
	File file = uploadFile.getFile();
	List<Obj> objList = new ArrayList<Obj>();
	if (file.exists()) {
	    List<List<String>> list = new ImportExcelUtil().getObjListByExcel(new FileInputStream(file),
		    file.getName());
	    for (List<String> object : list) {
		Obj obj = new Obj();
		obj.setName(String.valueOf(object.get(0)));
		obj.setSubject(String.valueOf(object.get(1)));
		obj.setType(String.valueOf(object.get(2)));
		obj.setLink(String.valueOf(object.get(3)));
		objList.add(obj);
	    }
	}
	this.renderJson(SysObj.me.insertObj(objList));
    }

    @RequiresPermissions(value = { "/sys/config" })
    public void userExport() {
	try {
	    SysUser user = IWebUtils.getCurrentSysUser(getRequest());
	    HttpServletResponse response = getResponse();
	    String path = new ImportExcelUtil().writeUserToExcel(SysUser.me.getAllUserList(user));
	    File file = new File(path);
	    if (file.exists()) {
		renderFile(file);
	    }
	} catch (Exception e) {
	    System.out.println(e.getMessage());
	}
    }

    @RequiresPermissions(value = { "/sys/config" })
    public void linkExport() throws FileNotFoundException, Exception {
	try {
	    String path = new ImportExcelUtil().writeObjToExcel(SysObj.me.getGrantObjList(getRequest()));
	    File file = new File(path);
	    if (file.exists()) {
		renderFile(file);
	    }
	} catch (Exception e) {
	    log.info(e.getMessage());
	}
    }

    @RequiresPermissions(value = { "/sys/config" })
    public void saveConfig() throws FileNotFoundException, Exception {
	String host = this.getPara("host");
	List<SysConfig> sysConfig = SysConfig.me.find("select * from sys_config where param = 'host'");
	sysConfig.get(0).set("value", host).update();
	this.renderJson(InvokeResult.success());
    }

}